package com.quyunshuo.module.home.room.dao

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.quyunshuo.module.home.room.entity.ConcentrationEntity
import com.quyunshuo.module.home.room.entity.PoetEntity
import kotlinx.coroutines.flow.Flow

@Dao
interface ConcentrationDao {
    // 插入
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(poet: ConcentrationEntity)

    // 插入多个
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertAll(poets: List<ConcentrationEntity>)

    @Query("SELECT *, id FROM concentration")
    suspend fun getAll():List<ConcentrationEntity>

    // 获取所有诗人
    @Query("SELECT * FROM concentration")
    fun getAllConcentration(): Flow<List<ConcentrationEntity>>

    // 按ID获取诗人
    @Query("SELECT * FROM concentration WHERE id = :id")
    fun getConcentrationById(id: Long): Flow<ConcentrationEntity>

    // 删除所有诗人
    @Query("DELETE FROM concentration  WHERE id = :id")
    suspend fun deleteById(id: Long):Int

    // 删除所有诗人
    @Query("DELETE FROM concentration")
    suspend fun deleteAll()

    // 新增：获取总专注分钟数（核心逻辑）
    @Query("SELECT COALESCE(SUM(duration_minutes), 0) FROM concentration")
    suspend fun getTotalMinutes(): Int
    /**
     * 获取总专注天数（去重日期）
     */
    @Query("SELECT COUNT(DISTINCT focus_date) FROM concentration")
    suspend fun getTotalFocusDays2(): Int

    /**
     * 获取总专注天数（去重日期）
     */
    @Query("SELECT COUNT(DISTINCT focus_date) FROM concentration")
    fun getTotalFocusDays(): Flow<Int>

    /**
     * 获取指定周的每日专注数据
     * @param startDate 周起始日期 (格式: yyyy-MM-dd)
     * @param endDate 周结束日期 (格式: yyyy-MM-dd)
     */
    @Query("""
        SELECT * 
        FROM concentration
        WHERE focus_date BETWEEN :startDate AND :endDate
        ORDER BY focus_date
    """)
    suspend fun getWeeklyDetails(startDate: String, endDate: String): List<ConcentrationEntity>
}